//! @Author: DengLibin
//! @Date: Create in 2024-07-17 14:18:57
//! @Description: 

use axum::{body::Body, response::{IntoResponse, Response}, Router};
use hyper::{header, HeaderMap, StatusCode};
use tokio::fs::File;
use tokio_util::io::ReaderStream;

pub mod hello_world;
pub mod user_controller;
pub mod date_time_controller;
pub mod task_controller;
pub mod tenant_login_controller;
pub mod template_obj;

/// @Author: DengLibin
 /// @Date: Create in 2024-07-24 09:22:16
 /// @Description: 下载文件
pub async fn download_file(file_path: &str, file_name: &str, file_size: usize)->hyper::Response<Body> {
     // 打开文件
     match File::open(file_path).await {
        Ok(file) => {
            // 创建一个 tokio 读流
            let stream = ReaderStream::new(file);

            // 创建 StreamBody
            let body = Body::from_stream(stream);

            // 创建响应头
            let mut headers = HeaderMap::new();
            headers.insert(
                header::CONTENT_TYPE,
                "application/octet-stream".parse().unwrap(),
            );
            headers.insert(
                header::CONTENT_DISPOSITION,
                format!("attachment; filename=\"{}\"", file_name)
                    .parse()
                    .unwrap(),
            );

            headers.insert(
                header::CONTENT_LENGTH,
                format!("{}", file_size).parse().unwrap(),
            );

            // 返回响应
            let mut res: hyper::Response<Body> = Response::new(body);
            let mut_status = res.status_mut();
            *mut_status = StatusCode::OK;

            res.headers_mut().extend(headers);

            res
        }
        Err(_) => {
            // 如果文件未找到，返回 404 Not Found
            StatusCode::NOT_FOUND.into_response()
        }
    }
}



/// @Author: DengLibin
/// @Date: Create in 2024-07-17 14:25:43
/// @Description: 注册controller路由
pub async fn register_controller(router: Router)->Router{
    let mut router = hello_world::route(router).await;
    router = user_controller::route(router).await;
    router = date_time_controller::route(router).await;
    router = task_controller::route(router).await;
    router = tenant_login_controller::route(router).await;
    router
}